package dhm.com.hpx.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dhm.com.hpx.R;
import dhm.com.hpx.adapter.OrderAdapter;
import dhm.com.hpx.base.BaseActivity;
import dhm.com.hpx.base.Presenter.PressenterImpl;
import dhm.com.hpx.base.netWork.Constant;
import dhm.com.hpx.base.netWork.LoginContract;
import dhm.com.hpx.entity.Bean;
import dhm.com.hpx.entity.MyOrderBean;
import dhm.com.hpx.entity.PayResult;
import dhm.com.hpx.entity.WacherBean;
import dhm.com.hpx.utils.SpUtils;

public class MyorderActivity extends BaseActivity implements LoginContract.IView , IWXAPIEventHandler {

    @BindView(R.id.text_nopay)
    TextView textNopay;
    @BindView(R.id.line_nopay)
    TextView lineNopay;
    @BindView(R.id.text_complete)
    TextView textComplete;
    @BindView(R.id.line_complete)
    TextView lineComplete;
    @BindView(R.id.recy)
    XRecyclerView recy;

    int page=1;

    private PressenterImpl pressenter;
    private String uid;
    private OrderAdapter orderAdapter;
    private List<MyOrderBean.DataBean> beanList;
    private int delposition;

    @Override
    protected int getLayout() {
        return R.layout.activity_myorder;
    }
    private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG:
                    PayResult payResult = new PayResult(((Map<String, String>) msg.obj));
                    String result1 = payResult.getResult();
                    if (payResult.getResultStatus().equals("9000")) {
                        Toast.makeText(getApplicationContext(), "支付成功", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(MyorderActivity.this, MainActivity.class);
                        intent.putExtra("paySuccess", 1);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        finish();
                    } else {
                        Toast.makeText(getApplicationContext(), payResult.getMemo(), Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
            }
        }
    };


    @Override
    protected void initView() {
        ButterKnife.bind(this);
        pressenter=new PressenterImpl();
        pressenter.attachView(this);

        uid = SpUtils.getString(this, "uid");

        LinearLayoutManager manager=new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recy.setLayoutManager(manager);
        recy.setLoadingMoreEnabled(true);
        recy.setPullRefreshEnabled(true);

        recy.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                page=1;
                getorder();
            }

            @Override
            public void onLoadMore() {
                getorder();
            }
        });
        showPopwindow();
        getorder();

    }


    private void getorder() {
        Map<String,String> map=new HashMap<>();
        map.put("token", Constant.TOKEN);
        map.put("uid",uid);
        map.put("status",orderStatus);
        map.put("page",page+"");
        pressenter.sendMessage(this,Constant.all_orders,map, MyOrderBean.class);
    }

    @Override
    protected void initData() {

    }

    String orderStatus="1";

    @SuppressLint("NewApi")
    @OnClick({R.id.back, R.id.nopay, R.id.complete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.nopay:
                orderStatus="1";
                textNopay.setTextColor(getResources().getColor(R.color.main));
                textComplete.setTextColor(Color.parseColor("#222222"));
                lineNopay.setVisibility(View.VISIBLE);
                lineComplete.setVisibility(View.INVISIBLE);
                page=1;
                getorder();
                break;
            case R.id.complete:
                orderStatus="2";
                textComplete.setTextColor(getResources().getColor(R.color.main));
                textNopay.setTextColor(Color.parseColor("#222222"));
                lineComplete.setVisibility(View.VISIBLE);
                lineNopay.setVisibility(View.INVISIBLE);
                page=1;
                getorder();
                break;
                default:
        }
    }

    int position=0;

    @Override
    public void requesta(Object data) {
        if (data instanceof MyOrderBean){
            MyOrderBean myOrderBean= (MyOrderBean) data;
            if (myOrderBean.getCode()==1){
                if (page==1){
                    recy.setVisibility(View.VISIBLE);
                    beanList = myOrderBean.getData();
                    orderAdapter = new OrderAdapter(this,orderStatus);
                    orderAdapter.setdeleteClick(new OrderAdapter.OnClick() {
                        @Override
                        public void item(int posttion,View view) {

                            if (beanList.get(posttion).getCoupon_status().equals("0")){
                                Map<String,String> map=new HashMap<>();
                                map.put("token",Constant.TOKEN);
                                map.put("uid",uid);
                                map.put("order_id", beanList.get(posttion).getOrderId()+"");
                                switch (beanList.get(posttion).getPayFrom()){
                                    case "1":
                                        pressenter.sendMessage(MyorderActivity.this,Constant.to_order_pay,map,WacherBean.class);
                                        break;
                                    case "2":
                                        pressenter.sendMessage(MyorderActivity.this,Constant.to_order_pay,map,String.class);
                                        break;
                                    default:
                                }
                            }else {
                                message=beanList.get(posttion).getCoupon_status_name()+",是否原价下单？";
                                setBackgroundAlpha(0.5f);
                                popWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
                            }
                        }
                    });
                    orderAdapter.setaddClick(new OrderAdapter.OnIntentClick() {
                        @Override
                        public void item(int position) {
                            delposition = position;
                            Map<String,String> map=new HashMap<>();
                            map.put("token",Constant.TOKEN);
                            map.put("uid",uid);
                            map.put("order_id",beanList.get(position).getOrderId()+"");
                            pressenter.sendMessage(MyorderActivity.this,Constant.del_order,map, Bean.class);
                        }
                    });
                    recy.setAdapter(orderAdapter);
                }else {
                    beanList.addAll(myOrderBean.getData());
                }
                orderAdapter.setList(beanList);

                page++;
                recy.refreshComplete();
                recy.loadMoreComplete();

            }else {
                if (page==1){
                    recy.setVisibility(View.GONE);
                }
                Toast.makeText(this, myOrderBean.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }else if (data instanceof WacherBean){
            if (data!=null){
                WacherBean wacherBean= (WacherBean) data;
                wxPay(wacherBean);
            }
        }else if (data instanceof String){
            if (data!=null){
                String orderInfo= (String) data;
                aliPay(orderInfo);
            }
        }if (data instanceof Bean){
            Bean bean= (Bean) data;
            Toast.makeText(this, bean.getMessage(), Toast.LENGTH_SHORT).show();
            if (bean.getCode()==1){
                beanList.remove(delposition);
                orderAdapter.setList(beanList);
            }
        }
    }


    String message="";

    private PopupWindow popWindow;

    private void showPopwindow() {
        View popView = View.inflate(this, R.layout.dialog_exit, null);
        TextView cancle = popView.findViewById(R.id.cancle);
        TextView title = popView.findViewById(R.id.title);
        TextView sure = popView.findViewById(R.id.sure);
        title.setText(message);
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popWindow.dismiss();
            }
        });
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Map<String,String> map=new HashMap<>();
                map.put("token",Constant.TOKEN);
                map.put("uid",uid);
                map.put("order_id", beanList.get(position).getOrderId()+"");
                switch (beanList.get(position).getPayFrom()){
                    case "1":
                        pressenter.sendMessage(MyorderActivity.this,Constant.to_order_pay,map,WacherBean.class);
                        break;
                    case "2":
                        pressenter.sendMessage(MyorderActivity.this,Constant.to_order_pay,map,String.class);
                        break;
                    default:
                }
                popWindow.dismiss();
            }
        });

        popWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popWindow.setFocusable(true);
        popWindow.setTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        popWindow.setOutsideTouchable(true);// 设置允许在外点击消失


        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // popupWindow隐藏时恢复屏幕正常透明度
                setBackgroundAlpha(1.0f);
            }
        });

    }


    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha 屏幕透明度0.0-1.0 1表示完全不透明
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }




    private void aliPay(final String orderInfo) {


        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(MyorderActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    private void wxPay(WacherBean wacherBean) {
        IWXAPI api = WXAPIFactory.createWXAPI(MyorderActivity.this, Constant.Wx_APP_ID);
        api.handleIntent(getIntent(),MyorderActivity.this);
        api.registerApp(Constant.Wx_APP_ID);
        PayReq req = new PayReq();

        req.appId = wacherBean.getAppid();
        req.partnerId = wacherBean.getPartnerid();
        req.prepayId = wacherBean.getPrepayid();
        req.packageValue = wacherBean.getPackageX();
        req.nonceStr = wacherBean.getNoncestr();
        req.timeStamp = wacherBean.getTimestamp();
        req.sign = wacherBean.getSign();
        api.sendReq(req);

    }




    @Override
    public void fail(String error) {

    }

    @Override
    public void onReq(BaseReq baseReq) {

    }
    final String TAG="微信支付结果";
    @Override
    public void onResp(BaseResp resp) {
        Log.d(TAG, "onPayFinish, errCode = " + resp.errCode);

        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {

            switch (resp.errCode) {
                case 0://支付成功
                    Toast.makeText(this, "支付成功", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "onResp: resp.errCode = 0   支付成功");
                    break;
                case -1://错误，可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等
                    Toast.makeText(this, "支付错误" + resp.errCode, Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "onResp: resp.errCode = -1  支付错误");
                    break;
                case -2://用户取消，无需处理。发生场景：用户不支付了，点击取消，返回APP。
                    Log.d(TAG, "onResp: resp.errCode = -2  用户取消");
                    Toast.makeText(this, "用户取消" + resp.errCode, Toast.LENGTH_SHORT).show();
                    break;
                default:
            }

            finish();//这里需要关闭该页面
        }
    }
}
